<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="信件标题" prop="letterTitle">
            <el-input
              v-model="queryParams.letterTitle"
              placeholder="请输入信件标题"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收件人" prop="receiverName">
            <el-input
              v-model="queryParams.receiverName"
              placeholder="请输入收件人"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="信件模式" prop="letterMode">
            <el-select v-model="queryParams.letterMode" placeholder="请选择信件模式" clearable style="width: 100%">
              <el-option label="电子信" value="electronic" />
              <el-option label="纸质信" value="paper" />
              <el-option label="公开信" value="public_post" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="状态" prop="letterStatus">
            <el-select v-model="queryParams.letterStatus" placeholder="请选择状态" clearable style="width: 100%">
              <el-option label="草稿" value="draft" />
              <el-option label="待付款" value="pending_payment" />
              <el-option label="处理中" value="processing" />
              <el-option label="已发送" value="sent" />
              <el-option label="已送达" value="delivered" />
              <el-option label="已归档" value="archived" />
              <el-option label="已发布" value="published" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="text-align: right; padding-top: 4px;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:letters:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:letters:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:letters:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:letters:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="lettersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="信件ID" align="center" prop="letterId" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="信件标题" align="center" prop="title" />
      <el-table-column label="信件内容" align="center" prop="content">
        <template slot-scope="scope">
          <div class="content-cell">{{ scope.row.content }}</div>
        </template>
      </el-table-column>
      <el-table-column label="信件模式" align="center" prop="letterMode">
        <template slot-scope="scope">
          <el-tag :type="getLetterModeType(scope.row.letterMode)" size="mini">
            {{ formatLetterMode(scope.row.letterMode) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="模板ID" align="center" prop="stationeryTemplateId" />
      <el-table-column label="收件人姓名" align="center" prop="recipientName" />
      <el-table-column label="收件人邮箱" align="center" prop="recipientEmail" />
      <el-table-column label="信件状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)" size="mini">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发送时间" align="center" prop="sentAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sentAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否匿名发布" align="center" prop="isAnonymousPublicPost">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isAnonymousPublicPost == 1 ? 'success' : 'info'" size="mini">
            {{ formatAnonymous(scope.row.isAnonymousPublicPost) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:letters:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:letters:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户信件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="信件标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入信件标题" />
        </el-form-item>
        <el-form-item label="信件模式" prop="letterMode">
          <el-select v-model="form.letterMode" placeholder="请选择信件模式" style="width: 100%" @change="handleLetterModeChange">
            <el-option label="电子信" value="electronic" />
            <el-option label="纸质信" value="paper" />
            <el-option label="公开信" value="public_post" />
          </el-select>
        </el-form-item>
        <el-form-item label="信件内容" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="模板ID" prop="stationeryTemplateId">
          <el-input v-model="form.stationeryTemplateId" placeholder="请输入信笺模板ID" />
        </el-form-item>
        <el-form-item label="收件人姓名" prop="recipientName">
          <el-input v-model="form.recipientName" placeholder="请输入收件人姓名" />
        </el-form-item>
        <el-form-item label="收件人邮箱" prop="recipientEmail" v-if="form.letterMode === 'electronic'">
          <el-input v-model="form.recipientEmail" placeholder="请输入收件人邮箱" />
        </el-form-item>
        <el-form-item label="发送时间" prop="sentAt" v-if="form.letterMode === 'electronic'">
          <el-date-picker clearable
            v-model="form.sentAt"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择发送时间">
          </el-date-picker>
          <div class="el-form-item__tip" style="color: #909399;">设置未来时间将自动创建定时发送任务</div>
        </el-form-item>
        <el-form-item label="信件状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择信件状态" style="width: 100%">
            <el-option label="草稿" value="draft" />
            <el-option label="待付款" value="pending_payment" />
            <el-option label="处理中" value="processing" />
            <el-option label="已发送" value="sent" />
            <el-option label="已送达" value="delivered" />
            <el-option label="已归档" value="archived" />
            <el-option label="已发布" value="published" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否匿名发布" prop="isAnonymousPublicPost" v-if="form.letterMode === 'public_post'">
          <el-switch
            v-model="form.isAnonymousPublicPost"
            active-text="是"
            inactive-text="否"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLetters, getLetters, delLetters, addLetters, updateLetters } from "@/api/system/letters";

export default {
  name: "Letters",
  data() {
    // 校验电子邮件格式
    const validateEmail = (rule, value, callback) => {
      if (this.form.letterMode === 'electronic' && (!value || value.trim() === '')) {
        callback(new Error('电子信件必须提供收件人邮箱'));
      } else if (value && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(value)) {
        callback(new Error('请输入正确的邮箱格式'));
      } else {
        callback();
      }
    };
    
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 信件表格数据
      lettersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        title: null,
        content: null,
        letterMode: null,
        stationeryTemplateId: null,
        recipientName: null,
        recipientEmail: null,
        status: null,
        createdAt: null,
        updatedAt: null,
        sentAt: null,
        isAnonymousPublicPost: null
      },
      // 表单参数
      form: {
        letterMode: "electronic", // 默认为电子信
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "信件标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "信件内容不能为空", trigger: "blur" }
        ],
        letterMode: [
          { required: true, message: "信件模式不能为空", trigger: "change" }
        ],
        recipientName: [
          { required: true, message: "收件人姓名不能为空", trigger: "blur" }
        ],
        recipientEmail: [
          { validator: validateEmail, trigger: "blur" }
        ],
        status: [
          { required: true, message: "信件状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户信件列表 */
    getList() {
      this.loading = true;
      listLetters(this.queryParams).then(response => {
        this.lettersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        letterId: null,
        userId: null,
        title: null,
        content: null,
        letterMode: "electronic", // 默认值
        stationeryTemplateId: null,
        recipientName: null,
        recipientEmail: null,
        status: "draft", // 默认为草稿
        createdAt: null,
        updatedAt: null,
        sentAt: null,
        isAnonymousPublicPost: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.dateRange && this.dateRange.length > 0) {
        this.queryParams.beginCreateTime = this.dateRange[0];
        this.queryParams.endCreateTime = this.dateRange[1];
      } else {
        this.queryParams.beginCreateTime = undefined;
        this.queryParams.endCreateTime = undefined;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.letterId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const letterId = row.letterId || this.ids
      getLetters(letterId).then(response => {
        this.form = response.data;
        // 确保isAnonymousPublicPost是数字类型
        if (this.form.isAnonymousPublicPost !== null && this.form.isAnonymousPublicPost !== undefined) {
          this.form.isAnonymousPublicPost = Number(this.form.isAnonymousPublicPost);
        }
        this.open = true;
        this.title = "修改用户信件";
      });
    },
    /** 信件模式变更处理 */
    handleLetterModeChange(value) {
      if (value === 'electronic') {
        // 电子信需要验证邮箱
        if (!this.form.status || this.form.status === '') {
          this.form.status = 'draft';
        }
      } else if (value === 'public_post') {
        // 公开信相关默认值
        this.form.isAnonymousPublicPost = 0;
        if (!this.form.status || this.form.status === '') {
          this.form.status = 'draft';
        }
      } else if (value === 'paper') {
        // 纸质信相关默认值
        if (!this.form.status || this.form.status === '') {
          this.form.status = 'draft';
        }
      }
      // 验证表单
      this.$nextTick(() => {
        this.$refs["form"]?.validateField('recipientEmail');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查电子信模式下是否有邮箱
          if (this.form.letterMode === 'electronic' && (!this.form.recipientEmail || this.form.recipientEmail.trim() === '')) {
            this.$message.error('电子信件必须提供有效的收件人邮箱');
            return;
          }
          
          if (this.form.letterId != null) {
            updateLetters(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLetters(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const letterIds = row.letterId || this.ids;
      this.$modal.confirm('是否确认删除用户信件编号为"' + letterIds + '"的数据项？').then(function() {
        return delLetters(letterIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/letters/export', {
        ...this.queryParams
      }, `letters_${new Date().getTime()}.xlsx`)
    },
    /** 格式化是否匿名发布 */
    formatAnonymous(isAnonymous) {
      if (isAnonymous === 1 || isAnonymous === '1' || isAnonymous === true || isAnonymous === 'true') {
        return '是';
      }
      return '否';
    },
    /** 格式化信件状态 */
    formatStatus(status) {
      if (!status) return '';
      const statusMap = {
        'draft': '草稿',
        'sent': '已发送',
        'processing': '处理中',
        'pending_payment': '待付款',
        'delivered': '已送达',
        'archived': '已归档',
        'published': '已发布'
      };
      return statusMap[status] || status;
    },
    /** 获取信件状态对应的标签类型 */
    getStatusType(status) {
      if (!status) return '';
      const statusTypeMap = {
        'draft': 'info',
        'sent': 'success',
        'processing': 'warning',
        'pending_payment': 'danger',
        'delivered': 'primary',
        'archived': 'info',
        'published': 'success'
      };
      return statusTypeMap[status] || 'info';
    },
    /** 格式化信件模式 */
    formatLetterMode(mode) {
      if (!mode) return '';
      const modeMap = {
        'electronic': '电子信',
        'paper': '纸质信',
        'public_post': '公开信'
      };
      return modeMap[mode] || mode;
    },
    /** 获取信件模式对应的标签类型 */
    getLetterModeType(mode) {
      if (!mode) return '';
      const modeTypeMap = {
        'electronic': 'primary',
        'paper': 'warning',
        'public_post': 'success'
      };
      return modeTypeMap[mode] || 'info';
    }
  }
};
</script>

<style scoped>
.content-cell {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  text-overflow: ellipsis;
  max-height: 60px;
  word-break: break-all;
  line-height: 20px;
  text-align: left;
  padding: 0 5px;
}
</style>
